<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/3/22
 * Time: 10:27
 */

namespace app\api\service;

use app\common\Model\OrderInfoShaohuo;
use app\common\Server\Redis;
use app\common\Service;
use think\Config;
use think\Db;

class JpushService extends Service
{
    public function makeOrder($order_id)
    {
        $order = OrderInfoShaohuo::get(['order_id' => $order_id]);
        $region_id = $order->region_id;
        $fc_id = $order->fc_id;

        $redis = new Redis();
        $hredis = $redis->handler();
        $region_redis = 'CACHE:REGION:USERS:' . $region_id;
        $uid_arr = $hredis->zrangebyscore($region_redis,date('YmdHis',time() - 3600*24),date('YmdHis'));

        if(empty($uid_arr)){
            return;
        }

        $user_list = Db::table('sh_user_shaohuo')
            ->field('u.mobile')
            ->alias('us')
            ->join('sh_user_shaohuo_funcs usf','us.uid = usf.uid')
            ->join('sh_user u','us.uid = u.uid')
            ->where("us.status = 1 and us.taking_status = 1 and usf.fc_id = {$fc_id} and usf.status = 1 and usf.user_status = 1")
            ->where("us.uid in (".implode(',',$uid_arr).")")
            ->select();

        $uids = [];
        foreach ($user_list as $item){
            $uids[] = $item['mobile'];
        }

        $str = '您有一个新订单!';
        $this->push($uids,$str);

    }

    private function push($addtags,$notification = 'jpush',$platform = 'all')
    {
        $jpush = Config::get('param.jpush');
        $app_key = $jpush['app_key'];
        $master_secret = $jpush['master_secret'];
        require __DIR__ .'/../../../vendor/jpush/jpush/autoload.php';
        $client = new \JPush\Client($app_key, $master_secret);

        $pusher = $client->push();
        $pusher->setPlatform($platform);
        $pusher->addTag($addtags);
        $pusher->androidNotification($notification);
        $pusher->iosNotification($notification,['sound' => 'new_order.caf']);
        try {
            $pusher->send();
        } catch (\JPush\Exceptions\JPushException $e) {
            return;
            // try something else here
            print $e;
        }
    }
}